<?php
/**
 * 蜘蛛抓取类（基类）
 */

abstract class Spider_Grabber_Abstract {

    /**
     * 缓存类实例
     * @var type
     */
    protected $_cache = null;

    /**
     * 缓存时间
     * @var type
     */
    protected $_cacheTime = null;

    /**
     * http 头里发送的 user_agent
     * @var type
     */
    protected $_userAgent = '';

    /**
     * 抓取超时
     * @var type
     */
    protected $_timeout = 0;

    /**
     * 登录用户名
     * @var type
     */
    protected $_username = '';

    /**
     * 登录密码
     * @var type
     */
    protected $_password = '';

    /**
     * 构造方法
     * 设置参数
     * @param type $option
     */
    public function  __construct($option = array()) {

        if (!empty($option['user_agent'])) {
            $this->_userAgent = $option['user_agent'];
        }
        if (!empty($option['timeout'])) {
            $this->_timeout = floatval($option['timeout']);
        }
        if (!empty($option['username'])) {
            $this->_username = $option['username'];
        }
        if (!empty($option['password'])) {
            $this->_password = $option['password'];
        }
        if (!empty($option['cache_time'])) {
            $this->_cacheTime = $option['cache_time'];
        }

        if (!empty($option['cache'])) {
            $this->_cache = Cache::factory($option['cache']['engine'], $option['cache']['option']);
        }
    }

    /**
     * 抓取链接
     */
	abstract public function fetchSource($url, $cookie = null, $httpHeader = null, $ignoreCache = false);

    /**
     * 获取缓存
     * @param <type> $url
     */
    protected function _fetchCache($url) {

        if (!$this->_cache) {
            return false;
        }

        try {
            return $this->_cache->load($url);
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * 设置缓存
     * @param <type> $url
     */
    protected function _saveCache($url, $html) {

        if (!$this->_cache || !$this->_cacheTime) {
            return false;
        }

        try {
            return $this->_cache->save($url, $html, $this->_cacheTime);
        } catch (Exception $e) {
            return false;
        }
    }
}